package com.dxb.test.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class RemoveCodeComment {
    public static final String url = "C:\\Users\\DLS\\Desktop\\user-center";
    public static final String suffix = ".java";
    /**
     * 匹配注释行
     */
    public static final Pattern DELETE = Pattern.compile("^\\s*\\*.*(Title|author|ClassName|Copyright|Company|@author|Date|@version|date).*");

    public static void main(String[] args) throws IOException {
        File file = new File(url);
        checkAndRemove(file);
    }

    /**
     * 检查并删除
     *
     * @param file 文件
     */
    private static void checkAndRemove(File file) throws IOException {
        if (file == null) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File file1 : files) {
                    checkAndRemove(file1);
                }
            }
            return;
        }
        if (file.getName().endsWith(suffix)) {
            doRemove(file);
        }
    }

    /**
     * 做删除
     *
     * @param file 文件
     */
    private static void doRemove(File file) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String s = input.readLine();
        List<String> code = new ArrayList<>();
        while (s != null) {
            code.add(s);
            s = input.readLine();
        }
        input.close();

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        for (String s1 : code) {
            if (DELETE.matcher(s1).matches() ) {
                continue;
            }
            out.write(s1);
            out.write("\n");
        }
        out.close();
    }
}
